﻿using System;
using System.Collections.Generic;
using System.Linq;
using Samurai.Infrastructure;

namespace Samurai.Crawler
{
    public class DirectoryBrowser : IDirectoryBrowser
    {
        public Func<CandidateMovie, bool> CandidateMovieFound { get; set; }

        private List<CandidateMovie> _candidateMovies;

        public List<CandidateMovie> GetCandidateMovies(string directoryPath)
        {
            _candidateMovies = new List<CandidateMovie>();

            var scanDirectory = new ScanDirectory();

            scanDirectory.DirectoryEvent += ScanDirectoryDirectoryEvent;
            scanDirectory.FileEvent += scanDirectory_FileEvent;

            scanDirectory.SearchPattern = "*.*";

            scanDirectory.WalkDirectory(directoryPath);

            var result = _candidateMovies.GroupBy(d => d.Path).Select(g => g.First()).ToList();

            return result;

        }

        void scanDirectory_FileEvent(object sender, FileEventArgs e)
        {

        }


        private void ScanDirectoryDirectoryEvent(object sender, DirectoryEventArgs e)
        {
            var candidateMovie = new CandidateMovie { Name = e.Info.Name, Path = e.Info.FullName };
            _candidateMovies.Add(candidateMovie);

            if (CandidateMovieFound != null)
                CandidateMovieFound(candidateMovie);
        }
    }
}
